package com.atguigu.flink0624.chapter07.timer;

import com.atguigu.flink0624.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/11/15 10:16
 */
public class Flink03_Timer_Project {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        env
            .socketTextStream("hadoop162", 9999)
            .map(line -> {
                String[] data = line.split(",");
                return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
            }).setParallelism(1)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((ws, ts) -> ws.getTs())
            )
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                // 和并行度有关, 和key没有关
                long timerTs;
                boolean isFirst = true;
                int lastVc;
                
                @Override
                public void onTimer(long timestamp,
                                    OnTimerContext ctx,
                                    Collector<String> out) throws Exception {
                    out.collect(ctx.getCurrentKey() + " 传感器的水位连续5s上升, 红色预警...");
                    isFirst = true;
                }
                
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    if (isFirst) {
                        isFirst = false;
                        // 第一条数据进来, 注册一个定时器
                        timerTs = value.getTs() + 5000;
                        ctx.timerService().registerEventTimeTimer(timerTs);
                    } else {
                        // 不是第一条, 判断水位是否上升
                        Integer currentVc = value.getVc();
                        if (currentVc <= lastVc) { // 水位没有上升. 删除定时器
                            System.out.println(value);
                            System.out.println("xxxxx");
                            ctx.timerService().deleteEventTimeTimer(timerTs); //
                            // 注册新的定时器
                            timerTs = value.getTs() + 5000;
                            ctx.timerService().registerEventTimeTimer(timerTs);
                        }
                    }
                    
                    lastVc = value.getVc();
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
